<template>
  <template v-for="(t, i) in items" :key="i">
    <button @click="navigate2url(t)" :style="t.style" :class="{ btnIcon: true, flex: typeof t.label === 'string' }">
      <template v-if="t.icon">
        <fab-icon :light="light" :type="t.icon" class="icon"></fab-icon>
      </template>
      <template v-if="t.label">
        <text class="text">{{ t.label }}</text>
      </template>
    </button>
  </template>
</template>

<script lang="ts" setup>
  import { computed } from 'vue'
  import fabIcon from '@/components/fab-icon/index.vue'

  type Props = {
    light : boolean
    buttonStyle : navbar.ButtonStyle
    buttons : Array<navbar.Button>
  }
  const props = defineProps<Props>()

  const items = computed(() => {
    return props.buttons.map((item) => {
      let t = {
        ...item,
      }
      if (typeof t.style === 'undefined') {
        t.style = {
          width: props.buttonStyle.width,
          height: props.buttonStyle.height,
        }
      }
      if (t.color) {
        t.style.color = t.color
      }
      if (t.background) {
        t.style.background = t.background
      }
      return t
    })
  })
  
  const navigate2url = (opts : navbar.Button)=> {
    let url = opts.url as string
    
    if (typeof opts.trigger === 'function') {
      url = opts.trigger.call(undefined) as string
    }
    
    if(typeof url === 'string') {
      if ('@back' == url) {
        uni.navigateBack({
          delta: 1,
        })
      } else {
        (opts.redirect ? uni.redirectTo : uni.navigateTo)({
          url,
          animationType: 'fade-in'
        })
      }
    }
  }
  
  // const navigate2url = (opts : navbar.Button) => {
  //   let url = opts.url as string
    
  //   if (typeof opts.trigger === 'function') {
  //     url = opts.trigger.call(undefined) as string
  //   }
    
  //   if(url) {
  //     if ('@back' == url) {
  //       uni.navigateBack({
  //         delta: 1,
  //       })
  //     } else {
  //       (opts.redirect ? uni.redirectTo : uni.navigateTo)({
  //         url,
  //         animationType: 'fade-in'
  //       })
  //     }
  //   }
  // }
</script>

<style lang="scss">
  .btnIcon {
    line-height: 1;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    margin: 0 6rpx 0 0;
    border: 0;
    position: relative;
    background: transparent;

    &::after {
      border: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }

    .icon {
      z-index: 2;
    }
  }

  .flex {
    flex: 1 !important;
    width: 0;
    padding: 0 8rpx;
    max-width: 140rpx;
    .text {
      line-height: 1;
      font-size: 28rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
</style>